package com.jfinal.weixin.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.util.Collection;
import java.util.HashMap;

public class ImageUtil {
//    public static void main(String[] args) {
//        getPicMediaId();
//
//    }
    public static String getPicMediaId(){
        try {
            String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxec3459db4cfa872e&secret=3eaba8af1b3fedc41f4194ca7d586809";
            String text = Jsoup.connect(getTokenUrl).ignoreContentType(true).get().body().text();
            JSONObject jsonObject =JSONObject.parseObject(text);
            String access_token = jsonObject.getString("access_token");
            String getPicDetail = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+access_token;

            Connection connect = Jsoup.connect(getPicDetail);
            String img_json = connect.header("Content-Type", "application/json").data("a", "b").requestBody("{\"type\": \"image\",\"offset\":0,\"count\":5}").ignoreContentType(true).post().body().text();
            //提取数据
            JSONObject get_img = JSONObject.parseObject(img_json);
            JSONArray imgArr = get_img.getJSONArray("item");
            String media_id="";
            for (int i=0;i<imgArr.size();i++){
                 media_id = imgArr.getJSONObject(0).getString("media_id");
            }
            //System.out.println(media_id);

            return media_id;


        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
}
